package com.iemes.util;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import com.iemes.entity.UserFormMap;

public class PasswordHelper {
	private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
	private String algorithmName = "md5";
	private int hashIterations = 2;

	public void encryptPassword(UserFormMap userFormMap) {
		String salt=randomNumberGenerator.nextBytes().toHex();
		userFormMap.put("credentials_salt", salt);
		String newPassword = new SimpleHash(algorithmName, userFormMap.get("password"), ByteSource.Util.bytes(userFormMap.get("account_name")+salt), hashIterations).toHex();
		userFormMap.put("password", newPassword); 
	}
	public static void main(String[] args) {
//		PasswordHelper passwordHelper = new PasswordHelper();
//		UserFormMap userFormMap = new UserFormMap();
//		userFormMap.put("password","123456");
//		userFormMap.put("accountName","admin");
//		passwordHelper.encryptPassword(userFormMap);
//		System.out.println(userFormMap);
		
		/*UserFormMap userFormMap = new UserFormMap();
		userFormMap.put("password", "f295cece8171e6ed82afa8cfab07a94c");
		userFormMap.put("credentials_salt", "accd5d7fda8aa02a3a4c1e40a5a2f594");
		userFormMap.put("account_name", "huahao");
		test(userFormMap);*/
		
		PasswordHelper passwordHelper = new PasswordHelper();
		String newPassword = passwordHelper.getEncryptPassword("admin", "123456", "aaacaf8c420b87eb1241422ec4339268");
		System.out.println(newPassword);
	}
	
	private static void test(UserFormMap userFormMap) {
		String salt = userFormMap.getStr("credentials_salt");
		String newPassword = new SimpleHash("md5", userFormMap.get("password"), ByteSource.Util.bytes(userFormMap.get("account_name")+salt), 2).toHex();
		System.out.println(newPassword);
	}
	
	public String getEncryptPassword(String account_name, String password, String credentials_salt) {
		return new SimpleHash(algorithmName, password, ByteSource.Util.bytes(account_name+credentials_salt), hashIterations).toHex();
	}
}
